package com.yzc.interceptor;


import com.yzc.util.JwtUtil;
import feign.RequestInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

@Slf4j
@Component
@RequiredArgsConstructor
public class FeignClientInterceptor {

    private final JwtUtil jwtUtil;

    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            try {
                String token = null;

                // 优先从 HttpServletRequest 中获取 JWT Token
                try {
                    HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
                    token = jwtUtil.resolveReqToken(request);
                } catch (Exception e) {
                    log.warn("无法从 HttpServletRequest 中获取 JWT Token，尝试从 Feign 请求头中获取");
                }

                // 如果从 HttpServletRequest 中未获取到，尝试从 Feign 请求头中获取
                if (token == null) {
                    token = template.headers().get("Authorization").stream()
                            .findFirst()
                            .map(header -> header.replace("Bearer ", "")) // 去掉 "Bearer " 前缀
                            .orElse(null);
                }

                // 如果成功获取到 JWT Token，添加到 Feign 请求头中
                if (token != null) {
                    template.header("Authorization", "Bearer " + token);
                }
            } catch (Exception e) {
                log.error("RequestInterceptor 处理失败", e);
            }
        };
    }
}